package com.ppp.searchHelp.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 工具类
 * 
 * @author song song571377@qq.com
 * @createDate 2015/10/03
 *
 */
public class StringUtil {

	
	public static boolean isBlank(String str){
		return str == null || str.trim().isEmpty();
	}
	
	/**
	 * 字符串转MAP
	 */
	public static Map<String, Object> stringToMap(String str){
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(isBlank(str)){
			return map;
		}
		
		return jsonToMap(new JSONObject(str));
	}
	
	/**
	 * JSONObject转MAP
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> jsonToMap(JSONObject obj){
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(obj == null){
			return map;
		}
		Iterator<String> iterator = obj.keys();
		
		String key = null;
		Object val = null;
		while(iterator.hasNext()){
			key = iterator.next();
			val = obj.get(key);
			if(val instanceof JSONObject){
				map.put(key, jsonToMap((JSONObject)val));
			}else{
				map.put(key, obj.get(key));
			}
		}
		return map;
	}
	
	/**
	 * JSONObject转Map<String, ArrayList<String>>
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, ArrayList<String>> jsonToMapValArray(JSONObject obj){
		Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
		Iterator<String> iterator = obj.keys();
		String key = null;
		JSONArray arryVal = null;
		ArrayList<String> list = null;
		while(iterator.hasNext()){
			key = iterator.next();
			arryVal = obj.getJSONArray(key);
			
			list = new ArrayList<String>();
			for(int i=0;i<arryVal.length();i++){
				list.add(arryVal.getString(i));
			}
			map.put(key, list);
		}
		
		return map;
	}
	
	
}
